<?php

//use Test;

class RController extends \Phalcon\Mvc\Controller
{

    const DATA_PATH = '/var/www/html/total/app/data/';

    public function indexAction() {
        echo 'this is index.';
    }
    
    public function gtAction() {
    
        $params = $this -> request -> get();
        $ttype = 'NP';
        if (isset($params['ttype'])) {
            $ttype = $params['ttype'];
        }

        $gtf = $this->execR('gtT.R', $ttype);
        
        $this->writeGT( self::DATA_PATH . 'gt' . $gtf);

    }

    public function crossAction() {
        
        $params = $this -> request -> get();
        if (empty($params['axis'])) {
            echo 'axis is required!';
            return;
        }
        
        $axis = $params['axis'];

        $this->execR('crossT.R', $axis);
    
    }


    private function execR($rscript, $params = null) {

        $args[] = "label-utf8.csv";
        $args[] = "rawdata-utf8.csv";
        
        $filenm = uniqid() . '.txt';
        $args[] = $filenm;

        array_push($args, $params);
        $args = implode(' ', $args);
        $args = escapeshellcmd($args);

        $rpath = '/var/www/html/total/app/r/';
        $rscript = $rpath . $rscript;
        $cmd = "R --vanilla --slave --args $args < $rscript";

echo $cmd . '<br/>';

        exec($cmd, $out, $ret);

        if ($ret == 0 ) {
            echo "→$rscript is well done.";
        
        } else {
            echo "→error is occured while run $rscript.";
        }

        return $filenm;

    }

    // 書式設定
    private function writeGT($filenm) {

        echo "<br/>" . $filenm . "<br/>";

        $handle = fopen($filenm, "r");

        // Excelライブラリ
        require_once dirname(__FILE__) . '/../lib/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        
        $objPHPExcel->getProperties()->setCreator("total system")
                    ->setLastModifiedBy("total system")
                    ->setTitle("GT集計表")
                    ->setSubject("GT集計表")
                    ->setDescription("this is generated by total system.");
                    
        $activeSheet = $objPHPExcel->getActiveSheet();
        $activeSheet->setTitle("GT集計表");

        // 書式設定
        $defaultStyles = array(
            'font' => array(
                'name' => 'ＭＳ ゴシック',
                'size' => 9,
                
            ),
        );

        $objPHPExcel->getDefaultStyle()->applyFromArray($defaultStyles);
        // デフォルト行の高さ
        $activeSheet->getDefaultRowDimension()->setRowHeight(17);

        // 全体セル
        $totalStyles =  array( 
            'alignment' => array( 
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ,
            ), 
        );
        
        // 設問文
        $qnmStyles =  array( 
            'alignment' => array( 
                'wrap' => true ,
            ), 
        );

        // カテゴリセル
        $catStyles = array( 
            'alignment' => array( 
                'rotation' => 255,
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP, 
            ), 
        );

        // N数セル
        $nStyles = array( 
            'numberformat' => array( 
                'code' => PHPExcel_Style_NumberFormat::FORMAT_NUMBER,
            ), 
        );
        
        // %数セル
        $pStyles = array( 
            'numberformat' => array( 
                'code' => '#0.0',
            ), 
        );

        // 出力開始行番号
        $rowno = 1;
        $colno = 3;
        
        $tdata = array();
        
        $isNU = false;
        
        // 空白行を設問の区切りとして、Excelファイルへ出力
        while (($buffer = fgets($handle)) !== false) {
        
            // 新しいアイテム
            if (preg_match('/^\n/', $buffer)) {

                // 前の設問の集計表を出力
                if (count($tdata) > 0) {
                    
//                    echo '<pre>';
//                    print_r($tdata);
//                    echo '<pre>';
                    
                    // データ加工（縦方向に変換）
                    $title = array_slice($tdata, 0, 2);
                    if (isset($tdata[4])) {
                        $isNU = false;
                    } else {
                        $isNU = true;
                    }
                    
                    if ($isNU) {
                        $gtdata = array_map(null, range(0, count($tdata[2]) - 1), $tdata[2], $tdata[3]);
                    } else {
                        $gtdata = array_map(null, range(0, count($tdata[2]) - 1), $tdata[2], $tdata[3], $tdata[4]);
                    }
                    // データ出力
                    $qrow = $rowno + 1;
                    $activeSheet->mergeCells("B$qrow:E$qrow");
                    $activeSheet->fromArray($title, NULL, 'A' . $rowno);
                    
                    $activeSheet->getCell('D'.($rowno+2))->setValue('回答数');
                    if (isset($tdata[4])) {
                        $activeSheet->getCell('E'.($rowno+2))->setValue('％');
                    }
                    
                    $activeSheet->fromArray($gtdata, NULL, 'B' . ($rowno+3));
                    
                    // 書式設定
                    
                    // 列幅
                    $activeSheet->getColumnDimension('A')->setWidth(10);
                    $activeSheet->getColumnDimension('B')->setWidth(6);
                    $activeSheet->getColumnDimension('C')->setWidth(50);
                    $activeSheet->getColumnDimension('D')->setWidth(10);
                    $activeSheet->getColumnDimension('E')->setWidth(10);
                    
                    // 設問文（なぜか改行を設定したら文字列は見えなくなる！！？）
                    //$activeSheet->getStyle("B$qrow")->applyFromArray($qnmStyles);
                    //$activeSheet->getStyle("B$qrow")->getAlignment()->setWrapText(true);
                    //$activeSheet->getRowDimension($qrow)->setRowHeight();
                    
                    // 回答数、％
                    $npRange = 'D' . ($rowno+2) . ':E' . ($rowno+2);
                    if ($isNU) {
                        $npRange = 'D' . ($rowno+2);
                    }
                    $activeSheet->getStyle($npRange)->getBorders()->getAllBorders()->setBorderStyle( 
                        PHPExcel_Style_Border::BORDER_THIN
                    );
                    $activeSheet->getStyle($npRange)->applyFromArray($totalStyles);
                    
                    // カテゴリ
                    $catrows = $rowno + 3;
                    $catrowe = $rowno + 3 + count($tdata[2]) - 1;
                    
                    // 全体セルマージ
                    $activeSheet->mergeCells("B$catrows:C$catrows");
                    $activeSheet->getCell("B$catrows")->setValue("全　　　体");
                    $activeSheet->getStyle("B$catrows")->applyFromArray($totalStyles);

                    // N数
                    $activeSheet->getStyle("D$catrows:D$catrowe")->applyFromArray($nStyles);
                    $tableRange = "B$catrows:D$catrowe";
                    
                    // %数
                    if (! $isNU) {
                        $activeSheet->getStyle("E$catrows:E$catrowe")->applyFromArray($pStyles);
                        
                        $tableRange = "B$catrows:E$catrowe";
                    }
                    
                    $activeSheet->getStyle($tableRange)->getBorders()->getAllBorders()->setBorderStyle( 
                        PHPExcel_Style_Border::BORDER_THIN
                    );

                    // 次の出力対象行
                    $rowno = $catrowe + 1;
                }
                // 前のデータをクリア
                unset($tdata);

            }
            
            $tdata[] = preg_split('/\t/', $buffer);

//             echo strlen($buffer);
//             echo $buffer;
//             echo "<br/>";
        }
         
        if (!feof($handle)) {
            echo "→Error: unexpected fgets() fail\n";
        }

        $ofilenm = str_replace('.txt', '.xlsx', $filenm);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        $objWriter->save($ofilenm);

        echo "→excel file $ofilenm is generated.\n";

    }

    // 書式設定（横方向出力）
    private function writeGTH($filenm) {

        echo "<br/>" . $filenm . "<br/>";

        $handle = fopen($filenm, "r");

        // Excelライブラリ
        require_once dirname(__FILE__) . '/../lib/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        
        $objPHPExcel->getProperties()->setCreator("total system")
                    ->setLastModifiedBy("total system")
                    ->setTitle("GT集計表")
                    ->setSubject("GT集計表")
                    ->setDescription("this is generated by total system.");
                    
        $activeSheet = $objPHPExcel->getActiveSheet();
        $activeSheet->setTitle("GT集計表");

        // 書式設定

        $defaultStyles = array(
            'font' => array(
                'name' => 'ＭＳ ゴシック',
                'size' => 9,
                
            ),
        );

        $objPHPExcel->getDefaultStyle()->applyFromArray($defaultStyles);

        // カテゴリセル
        $catStyles = array( 
            'alignment' => array( 
                'rotation' => 255,
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP, 
            ), 
        );

        // N数セル
        $nStyles = array( 
            'numberformat' => array( 
                'code' => PHPExcel_Style_NumberFormat::FORMAT_NUMBER,
            ), 
        );
        
        // %数セル
        $pStyles = array( 
            'numberformat' => array( 
                'code' => '#0.0',
            ), 
        );

        // 出力開始行番号
        $rowno = 1;
        $colno = 3;
        
        $tdata = array();
        
        // 空白行を設問の区切りとして、Excelファイルへ出力
        while (($buffer = fgets($handle)) !== false) {
        
            // 新しいアイテム
            if (preg_match('/^\n/', $buffer)) {

                // 前の設問の集計表を出力
                if (count($tdata) > 0) {
                    
//                    echo '<pre>';
//                    print_r($tdata);
//                    echo '<pre>';
                    
                    // データ加工
                                        
                    // データ出力
                    $activeSheet->fromArray($tdata, NULL, 'A' . $rowno);
                    
                    // 書式設定
                    $colt = PHPExcel_Cell::stringFromColumnIndex(count($tdata[2]) - 1);

                    // カテゴリ
                    $catrow = $rowno + 2;
                    // 縦書き
                    //$activeSheet->getStyle("A$catrow:Z$catrow")->getAlignment()->setTextRotation(255);
                    $activeSheet->getStyle("A$catrow:Z$catrow")->applyFromArray($catStyles);
                    // 高さ
                    $activeSheet->getRowDimension($catrow)->setRowHeight(132);
                    
                    // N数
                    $nrow = $rowno + 3;
                    $activeSheet->getStyle("A$nrow:$colt$nrow")->applyFromArray($nStyles);
                    
                    $tableRange = "A$catrow:$colt$nrow";
                    
                    // %数
                    if (count($tdata) > 4) {
                        $prow = $rowno + 4;
                        $activeSheet->getStyle("A$prow:$colt$prow")->applyFromArray($pStyles);
                        
                        $tableRange = "A$catrow:$colt$prow";
                    }
                    
                    $activeSheet->getStyle($tableRange)->getBorders()->getAllBorders()->setBorderStyle( 
                        PHPExcel_Style_Border::BORDER_THIN
                    );
                    

                    // 次の出力対象行
                    $rowno = $rowno + count($tdata);
                }
                // 前のデータをクリア
                unset($tdata);

            }
            
            $tdata[] = preg_split('/\t/', $buffer);

//             echo strlen($buffer);
//             echo $buffer;
//             echo "<br/>";
        }
         
        if (!feof($handle)) {
            echo "→Error: unexpected fgets() fail\n";
        }

        $ofilenm = str_replace('.txt', '.xlsx', $filenm);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        $objWriter->save($ofilenm);

        echo "→excel file $ofilenm is generated.\n";

    }
    
    
    // 書式コピー
    private function writeGT2($filenm) {

        echo "<br/>" . $filenm . "<br/>";

        $handle = fopen($filenm, "r");

        // Excelライブラリ
        require_once dirname(__FILE__) . '/../lib/PHPExcel.php';
        
        // テンプレート
        $tpFileName = dirname(__FILE__) . '/../template/GT_Template.xlsx';
        $objPHPExcel = PHPExcel_IOFactory::load($tpFileName);

        $tpSheet = $objPHPExcel->getSheetByName("template");
        $catStyle = $tpSheet->getStyle('C5');

//        $objPHPExcel = new PHPExcel();
        
        $objPHPExcel->getProperties()->setCreator("total system")
                    ->setLastModifiedBy("total system")
                    ->setTitle("GT集計表")
                    ->setSubject("GT集計表")
                    ->setDescription("this is generated by total system.");

        $activeSheet = $objPHPExcel->createSheet();
        $activeSheet->setTitle("GT集計表");

        // 出力開始行番号
        $rowno = 1;
        $colno = 3;
        
        $tdata = array();
        
        // 空白行を表の区切りとして、Excelファイルへ出力
        while (($buffer = fgets($handle)) !== false) {
        
            // 新しいアイテム
            if (preg_match('/^\n/', $buffer)) {

                // 前のアイテムデータを出力
                if (count($tdata) > 0) {

                    // $tdata（1行目：空白、2行目：質問、3行目：カテゴリ名、4行目：N値、5行目：P値）
//                    echo '<pre>';
//                    print_r($tdata);
//                    echo '<pre>';
                    
                    $activeSheet->fromArray($tdata, NULL, 'A' . $rowno);
                    
                    // 書式設定
                    $colt = PHPExcel_Cell::stringFromColumnIndex(count($tdata[2]) - 1);
                    
                    // カテゴリ
                    $catrow = $rowno + 2;
                    $activeSheet->duplicateStyle($catStyle, "A$catrow:$colt$catrow");
                    $activeSheet->getRowDimension($catrow)->setRowHeight(132);
                    
                    // N数
/*                    $nrow = $rowno + 3;
                    $activeSheet->getStyle("A$nrow:$colt$nrow")->getNumberFormat()->setFormatCode(
                        PHPExcel_Style_NumberFormat::FORMAT_NUMBER
                    );
                    
                    // %数
                    $prow = $rowno + 4;
                    $activeSheet->getStyle("A$prow:$colt$prow")->getNumberFormat()->setFormatCode(
                        PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 
                    );
                    
                    $activeSheet->getStyle("A$nrow:$colt$prow")->getBorders()->getAllBorders()->setBorderStyle( PHPExcel_Style_Border::BORDER_THIN );
*/
                    // 次の出力対象行
                    $rowno = $rowno + count($tdata);
                }
                // 前のデータをクリア
                unset($tdata);

            }
            
            $tdata[] = preg_split('/\t/', $buffer);

//             echo strlen($buffer);
//             echo $buffer;
//             echo "<br/>";
        }
         
        if (!feof($handle)) {
            echo "→Error: unexpected fgets() fail\n";
        }
        
        // template シートを削除
        $objPHPExcel->removeSheetByIndex($objPHPExcel->getIndex($tpSheet));

        $ofilenm = str_replace('.txt', '.xlsx', $filenm);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        $objWriter->save($ofilenm);

        echo "→excel file $ofilenm is generated.\n";

    }


}         


